package com.ams.server.replication;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ams.io.network.connection.Connection;
import com.ams.io.network.connection.SocketConnector;
import com.ams.protocol.rtmp.RtmpConnection;
import com.ams.protocol.rtmp.RtmpHandShake;
import com.ams.server.handler.ProtocolHandler;

public class ReplSubscribeHandler extends ProtocolHandler {
    final private Logger logger = LoggerFactory
            .getLogger(ReplSubscribeHandler.class);
    private static final int CONNECT_RETRY_INTERVAL = 5 * 1000;

    private String publisherHost = null;
    private int publisherPort;

    private RtmpConnection rtmp;
    private RtmpHandShake handshake;
    private boolean keepAlive = true;
    private ReplSubscriber subscriber;
    private ConcurrentLinkedQueue<String> subscriptionQueue = new ConcurrentLinkedQueue<String>();

    public ReplSubscribeHandler(String host, int port) {
        this.publisherHost = host;
        this.publisherPort = port;
    }

    private boolean connectToPublisher() {
        logger.info("connect to publisher {}:{} ...", publisherHost,
                publisherPort);
        try {
            SocketConnector conn = SocketConnector
                    .connect(new InetSocketAddress(publisherHost, publisherPort));
            setConnection(conn);
            logger.info("connected.");
        } catch (IOException e) {
            logger.info("connect error");
            return false;
        }
        return true;
    }

    private void doClientHandshake() {
        logger.info("publisher rtmp handshake...");
        while (!handshake.isHandshakeDone()) {
            try {
                handshake.doClientHandshake();
                // write to socket channel
                conn.flush();
            } catch (Exception e) {
                break;
            }
        }
    }

    private void handshakePublisher() {
        if (!connectToPublisher()) {
            logger.info("connect to publisher error, retry.");
            try {
                Thread.sleep(CONNECT_RETRY_INTERVAL);
            } catch (InterruptedException e) {
            }
            return;
        }
        // do client handshake
        doClientHandshake();
        logger.info("replication rtmp handshake done.");
    }

    public void run() {
        if (conn == null || conn.isClosed()) {
            handshakePublisher();
        }

        try {
            // wait&process publish command from publisher.
            subscriber.acceptPublisherCommand();
            
            // subscribe
            String streamName = subscriptionQueue.poll();
            if (streamName != null) {
                logger.info("subscribe stream: {}", streamName);
                subscriber.sendSubscriptionCommand(streamName);
            }

            Thread.sleep(10);

            conn.flush();
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
    }
    
    public void subscribe(String streamName) {
        subscriptionQueue.add(streamName);
    }
    
    public void setConnection(Connection conn) {
        this.conn = conn;
        this.rtmp = new RtmpConnection(conn);
        this.subscriber = new ReplSubscriber(rtmp);
        this.handshake = new RtmpHandShake(rtmp);
    }

    public boolean isKeepAlive() {
        return keepAlive;
    }

    public ProtocolHandler handlerFactory() {
        return null;
    }

    public void close() {
        conn.close();
        keepAlive = false;
    }

}